var napa = require("napajs");
const baseUrl = "../images/";
var fs = require('fs');
var imgHash = require('./imghash1.js');
var iconv = require('iconv-lite');

function readDir(cname, hashTemp) {
	var reg = /.*[\u4e00-\u9fa5]+.*$/;
	var baseUrl = "../images/";
	var results = [];
	var hasChinese = reg.test(cname);
	var filePath = "../images_hash/" + cname + ".json";
	console.log(cname + "------" + hasChinese);
	if (hasChinese) {
		filePath = "../images_hash/" + encodeURIComponent(cname) + ".json";
		console.log(filePath)
	}
	try {
		var imgobj = JSON.parse(require('fs').readFileSync(filePath).toString());
		Object.keys(imgobj).forEach((k) => {
			var hash2 = imgobj[k];
			var dist = require('hamming-distance')(hashTemp, hash2);
			if(dist <= 17) {
				results.push({
					img: k,
					dist: dist,
					cname: cname
				});
			}
		});
	} catch(e) {
		console.log(decodeURIComponent(e));
	}
	return results;
}

function searchRun(hashTemp, num, cnames) {

	cnames = cnames || fs.readdirSync("../images/"); 
	var NUMBER_OF_WORKERS = cnames.length;
	//Each search can't share one zone, how to eliminate the zone when the search is finished?'
	var zone = napa.zone.create('zone' + num, {
		workers: NUMBER_OF_WORKERS
	});
	console.log("zone" + num + "created!");
	var reg1 = /[\u4e00-\u9fa5]*/g;
	var reg2 = /[A-Z]*/g;
	var promises = [];
	var r = {};
	for(var i = 0; i < cnames.length; i++) {
		promises[i] = zone.execute(readDir, [cnames[i], hashTemp]);
	}
	
	return Promise.all(promises).then(values => {	
		for (var i = 0; i < values.length; i++) {
			var t = JSON.parse(values[i]._payload);
			if (t.length > 0) {
				var c = t[0].cname;
				r[c] = t;
			}
		}
		console.log("========Search done!========");
		return r;
	});
}

module.exports = {
	readDir,
	searchRun
}
